import { ref } from 'vue';
import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';
import { loginApi } from '@/api';
import { useAccessStore, resetAllStores, useUserStore } from '@/store';
import { LOGIN_PATH, DEFAULT_HOME_PATH } from '@/constants';

export const useAuthStore = defineStore('AuthStore', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);
  // 登录
  async function userLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    try {
      loginLoading.value = true;
      const userInfo = await loginApi(params);
      // 将token存在accessStore中
      userInfo.token && accessStore.setAccessToken(userInfo.token);
      // 将userInfo存在userStore中
      userStore.setUserInfo(userInfo);
      if (accessStore.loginExpired) {
        accessStore.setLoginExpired(false);
      } else {
        onSuccess ? await onSuccess?.() : await router.push(DEFAULT_HOME_PATH);
      }
    } finally {
      loginLoading.value = false;
    }
  }
  // 退出登录
  async function logout(redirect: boolean = true) {
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }
  function $reset() {
    loginLoading.value = false;
  }

  return {
    userLogin,
    logout,
    $reset,
  };
});
